@auth.requires_login()
def index():
    redirect(URL('quiz', 'index'))
    return

@auth.requires_login()
def download():
    import os
    import shutil
    import uuid
    import time
    import zipfile
    import contenttype as c
    from PIL import Image
    
    memberships = db(db.auth_membership.user_id==auth.user_id)._select(db.auth_membership.group_id) or redirect(URL('index'))
    row = db((db.auth_group.id.belongs(memberships)) & (db.auth_group.id==request.args(0)) & (~db.auth_group.role.contains(['user_', 'admins'], all=False))).select(db.auth_group.ALL, db.stats.ALL, orderby=~db.stats.total, left=db.stats.on(db.auth_group.id==db.stats.group_id)).first() or redirect(URL('index'))

    #quiz is either personal or regional
    quiz = row.auth_group.quiz[4:]
    group_id = row.auth_group.id
    
    if quiz == 'personal':
        content=db(db.quizpersonal.group_id == group_id).select()
    elif quiz == 'regional':
        content=db(db.quizregional.group_id == group_id).select()
   
    folderLocation = '%sexports/%s/quiz_%s' % (request.folder, group_id, quiz)
    zipLocation = '%sexports/%s/quiz_%s.zip' % (request.folder, group_id, quiz)
    
#    if os.path.exists(folderLocation):
#        return
    
    if os.path.isfile(zipLocation):
        zipNewLocation = '%sexports/%s/quiz_%s_%s.zip' % (request.folder, group_id, quiz, time.strftime("%Y-%m-%d_%H-%M-%S"))
        #shutil.move(zipLocation, zipNewLocation)
        systemCMD = "mv %s %s" % (zipLocation, zipNewLocation)
        os.system(systemCMD)

    for i in range(len(content)):
        content[i].quiz = quiz
        if content[i].file:
            fileOrgName = content[i].file
            fileName = 'game_quiz%s_%s_width_390.jpg' % (quiz, content[i].id)
            fileLocation = '%sexports/%s/quiz_%s/Images/%s' % (request.folder, group_id, quiz, fileName)
            resizeImage(fileOrgName, 390, fileLocation, "jpg", "JPEG")
            #ADD fields for SQL file
            content[i].resizedfile = 'static/images/thumbs/390/%s.jpg' % (os.path.splitext(fileOrgName)[0])
            #content[i].file = fileName
            content[i].filesize = os.path.getsize(fileLocation)
            #content[i].filesize = 0
        else:
            content[i].resizedfile = ''
            content[i].filesize = ''
            
    d = os.path.dirname('%s/' % (folderLocation))
    if not os.path.exists(d):
        os.makedirs(d)
    
    #os.chdir(folderLocation)
    sqlContent = response.render('export/content.html', content=content)
    sqlLocation = '%sexports/%s/quiz_%s/content.sql' % (request.folder, group_id, quiz)
    optionsContent = response.render('export/options.html')
    optionsLocation = '%sexports/%s/quiz_%s/options.rc' % (request.folder, group_id, quiz)
    sqlFile = open(sqlLocation, 'w+')
    sqlFile.write(sqlContent)
    sqlFile.close()
    optionsFile = open(optionsLocation, 'w+')
    optionsFile.write(optionsContent)
    optionsFile.close()  
    #os.chdir(request.global_settings.gluon_parent)
    
    os.chdir('%sexports/%s' % (request.folder, group_id))
    systemMOD = 'chmod -R 777 quiz_%s' % (quiz)
    os.system(systemMOD)
    systemCMD = 'zip -rq -P "Stas roelt ook nu als een gek" quiz_%s.zip quiz_%s' % (quiz, quiz)
    os.system(systemCMD)
    systemMOD = 'chmod 777 quiz_%s.zip' % (quiz)
    os.system(systemMOD)
    os.chdir(request.global_settings.gluon_parent)

    if os.path.isfile(zipLocation):
        systemCMD = 'rm -rf %s' % (folderLocation)
        os.system(systemCMD)

    zipName = 'quiz_%s.zip' % (row.auth_group.quiz[4:])
    #zipLocation = '%sexports/%s/quiz_%s.zip' % (request.folder, row.auth_group.id, row.auth_group.quiz[4:])
    response.headers['Content-Type'] = c.contenttype(zipLocation)
    response.headers['Content-Disposition'] = 'attachment; filename=%s' % (zipName) # to force download as attachment
    return response.stream(open(zipLocation,'rb'),chunk_size=4096)